package consul

import (
	consulapi "github.com/hashicorp/consul/api"
)

const (
	CheckUrl = "http://127.0.0.1:8080/check"
)

type ConsulParam struct {
	Id string
	Name string
	Tags []string
	Port int
	Address string
	CheckInterval int
	CheckTimeout int
}

var consulConfig *consulapi.Config
var consulClent *consulapi.Client

func init()  {
	consulConfig = consulapi.DefaultConfig()
	consulConfig.Address = "127.0.0.1:8500"
	client,err := consulapi.NewClient(consulConfig)
	if err != nil {
		panic(err)
	}
	consulClent = client
}

func getClient() *consulapi.Client {
	if consulClent == nil {
		client,err := consulapi.NewClient(consulConfig)
		if err == nil {
			consulClent = client
		}
	}
	return consulClent
}

func RegistServie(param *ConsulParam) (bool,error) {
	client := getClient()
	service := &consulapi.AgentServiceRegistration{
		ID:param.Id,
		Name:param.Name,
		Tags:param.Tags,
		Address:param.Address,
		Port:param.Port,
		Check:&consulapi.AgentServiceCheck{
			HTTP:CheckUrl,
			Interval:param.CheckInterval + "s",
			Timeout:param.CheckTimeout + "s",
		},

	}
	err := client.Agent().ServiceRegister(service)
	if err != nil {
		return false,err
	}
	return true,nil
}
